import Taro from "@tarojs/taro";
import { reactive } from "vue";
import { getUserInfo } from "@/utils/storage";
import {
  carsQuery,
  listByTruckName,
  carsQueryById,
  saveSelfHkCar,
} from "./api";
import { useTzRouter } from "@/vhooks/useTzRouter";
export const useSearchCar = (state) => {
  //搜索车辆区域数据
  const searchForm = reactive({
    searchValue: "",
    carList: [],
    isSearchShow: false,
    className: "",
    addCarButShow: false,
  });
  //车辆信息数据
  const carForm = reactive({
    isAdd: false, //是否是新增车辆信息
    isEdit: false, //是否是编辑车辆信息
    formData: {}, //车辆信息data
  });

  //查看更多显示查询条件
  const moreClick = () => {
    searchForm.isSearchShow = true;
  };

  //默认查询车辆
  const initCarList = () => {
    carsQuery().then((res) => {
      searchForm.carList = res.data.recordList.filter((item) => {
        item.id = item.truckId;
        return item.hkTruckLicenseName;
      });
    });
  };
  initCarList();

  //清空
  const handleClear = () => {
    initCarList();
  };
  //根据关键字查询车辆
  const getCarList = () => {
    const data = {
      param: searchForm.searchValue,
      queryType: true,
    };
    listByTruckName(data).then((res) => {
      searchForm.carList = res.data.filter((item) => {
        item.hkTruckLicenseName = item.truckLicenseNameHongKong;
        return item.hkTruckLicenseName;
      });
    });
  };

  //根据id获取车辆信息
  const editCar = (id) => {
    const data = {
      param: id,
    };
    carsQueryById(data).then((res) => {
      carForm.formData = res.data[0];
      carForm.isEdit = true;
    });
  };

  //根据当前登录用户判断新增司机权限
  const userInfo = getUserInfo();
  if (userInfo?.userType?.isPersonal) {
    searchForm.addCarButShow = true;
  }

  //新增车辆信息
  const addCar = () => {
    carForm.isAdd = true;
    carForm.formData = {};
    if (userInfo?.userType?.isPersonal) {
      carForm.formData.dMobile = userInfo?.name;
    }
  };

  const editCarHook = useEditCar(carForm, state);
  return () => (
    <>
      <tz-view class="section ptb5">
        <tz-cell
          title={
            !carForm.isAdd && !carForm.isEdit
              ? "车辆选择"
              : carForm.isAdd
              ? "新增车辆"
              : "编辑车辆"
          }
          border
          class="textRight"
        >
          <tz-button
            type="primary"
            size="small"
            v-show={!carForm.isAdd && searchForm.addCarButShow}
            onClick={addCar}
          >
            新增车辆
          </tz-button>
        </tz-cell>
      </tz-view>
      <tz-view class="search" v-show={!carForm.isAdd}>
        <tz-view>
          <tz-text
            onClick={moreClick}
            v-show={!searchForm.isSearchShow && searchForm.carList.length > 9}
          >
            查看更多
          </tz-text>
          <tz-view class="search-form" v-show={searchForm.isSearchShow}>
            <tz-search
              prefix-icon="search"
              v-model={searchForm.searchValue}
              placeholder="输入车牌查询"
              clearable
              round
              showAction
              type="text"
              onClear={handleClear}
              onSearch={searchForm.searchValue ? getCarList : initCarList}
            ></tz-search>
          </tz-view>
        </tz-view>
        <tz-view class="car-list">
          {searchForm.carList.map((item, index) =>
            index < 9 ? (
              <tz-view key={index} onClick={() => editCar(item.id)}>
                <text
                  class={
                    item.hkTruckLicenseName ===
                    carForm.formData.hkTruckLicenseName
                      ? "selected"
                      : ""
                  }
                >
                  {item.hkTruckLicenseName}
                </text>
              </tz-view>
            ) : (
              ""
            )
          )}
        </tz-view>
      </tz-view>
      {editCarHook()}
    </>
  );
};

export const useEditCar = (carForm, state) => {
  //校验表单数据
  const checkFormData = (formData) => {
    // 内地车牌
    if (!formData.hkTruckLicenseName) {
      Taro.showToast({
        title: "请输入香港车牌",
        icon: "none",
        duration: 2000,
      });
      return false;
    }

    if (!/^[a-zA-Z0-9]*$/.test(formData.hkTruckLicenseName)) {
      Taro.showToast({
        title: "香港车牌格式有误,只能输入数字或字母",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    // ROCARS 登陆账号
    if (!formData.hkDriverCode) {
      Taro.showToast({
        title: "请输入ROCARS账号",
        icon: "none",
        duration: 2000,
      });
      return false;
    }

    if (!/^[A-Z0-9]*$/.test(formData.hkDriverCode)) {
      Taro.showToast({
        title: "ROCARS账号只能输入字母或数字",
        icon: "none",
        duration: 2000,
      });
      return false;
    }

    // 司机姓名
    if (!formData.driverName) {
      Taro.showToast({
        title: "请输入司机姓名",
        icon: "none",
        duration: 2000,
      });
      return false;
    }

    if (!/^[\u4e00-\u9fa5]{1,6}$/.test(formData.driverName)) {
      //!verify.isChinese(, 6)) {
      Taro.showToast({
        title: "司机姓名只能输入汉字，最多6位",
        icon: "none",
        duration: 2000,
      });
      return false;
    }
    if (formData.dMobile && !/^\d{1}[\d,-]{3,}\d{1}$/.test(formData.dMobile)) {
      Taro.showToast({
        title: "大陆手机号码格式有误! 例:13618181818,0755-2156245",
        icon: "none",
        duration: 2000,
      });
      return false;
    }

    if (formData.dMobile && formData.dMobile.indexOf(",") > -1) {
      Taro.showToast({
        title: "大陆手机号码只能输入一个",
        icon: "none",
        duration: 2000,
      });
      return false;
    }

    if (formData.hkDMobile && !/^[0-9]*$/.test(formData.hkDMobile)) {
      Taro.showToast({
        title: "香港手机号码格式有误! 只能输入数字",
        icon: "none",
        duration: 2000,
      });
      return false;
    }

    if (formData.hkDMobile && formData.hkDMobile.indexOf(",") > -1) {
      Taro.showToast({
        title: "香港手机号码只能输入一个",
        icon: "none",
        duration: 2000,
      });
      return false;
    }

    return true;
  };
  //获取页面地址参数
  const { navigateBack, route } = useTzRouter();
  //通过页面地址参数显示是否编辑车辆信息
  if (route.query.carInfo) {
    carForm.formData = JSON.parse(route.query.carInfo);
    carForm.isEdit = true;
  }

  const cancelClick = () => {
    navigateBack();
  };

  const sureClick = () => {
    //保存车辆信息
    const data = { ...carForm.formData };
    //校验表单数据
    if (!checkFormData(data)) {
      return;
    }
    Taro.showLoading({
      title: "",
    });
    state.handleBtnDisabled = true;
    saveSelfHkCar(data)
      .then(() => {
        Taro.hideLoading();
        state.handleBtnDisabled = false;
        navigateBack({
          delta: 1,
          event: {
            type: "bundleHomeBack", //事件类型 ，可以自己任意定义
            data: data, //回退的数据
          },
        });
      })
      .catch((err) => {
        console.log(err);
        Taro.hideLoading();
        state.handleBtnDisabled = false;
      });
  };

  return () => (
    <>
      <tz-view class="car-form" v-show={carForm.isEdit || carForm.isAdd}>
        <tz-cell title="香港车牌" border required>
          <tz-input
            v-model={carForm.formData.hkTruckLicenseName}
            type="text"
            placeholder="请输入香港车牌"
            clearable
            rules={(val) => {
              const value = val?.match(/[a-zA-Z0-9]{0,8}/g)?.[0] || "";
              return value.toUpperCase();
            }}
          />
        </tz-cell>
        <tz-cell title="司机姓名" border required>
          <tz-input
            v-model={carForm.formData.driverName}
            type="text"
            placeholder="请输入司机姓名"
            clearable
          />
        </tz-cell>
        <tz-cell title="rocars账号" border required>
          <tz-input
            maxlength="10"
            v-model={carForm.formData.hkDriverCode}
            type="number"
            placeholder="请输入rocars账号"
            clearable
          />
        </tz-cell>
        <tz-cell title="大陆手机号码" border>
          <tz-input
            v-model={carForm.formData.dMobile}
            type="number"
            placeholder="请输入大陆手机号码"
            maxlength="11"
            clearable
          />
        </tz-cell>
        <tz-cell title="香港手机号码">
          <tz-input
            v-model={carForm.formData.hkDMobile}
            type="number"
            maxlength="11"
            placeholder="请输入香港手机号码"
            clearable
          />
        </tz-cell>
      </tz-view>
      <tz-view class="btn-view">
        <tz-button
          disabled={state.handleBtnDisabled}
          class="save-btn"
          onClick={cancelClick}
        >
          取消
        </tz-button>
        <tz-button
          disabled={state.handleBtnDisabled}
          class="save-btn"
          type="primary"
          onClick={sureClick}
        >
          确定
        </tz-button>
      </tz-view>
    </>
  );
};
